import {
    Cartesian2,
    Cartesian3,
    Cartographic,
    Color,
    ColorMaterialProperty,
    createGuid,
    EasingFunction,
    EllipsoidGeodesic,
    HeightReference,
    HorizontalOrigin,
    LabelGraphics,
    LabelStyle,
    Math as CesiumMath,
    PolylineDashMaterialProperty,
    Rectangle,
    SceneMode,
    ScreenSpaceEventHandler,
    ScreenSpaceEventType,
    VerticalOrigin,
} from 'cesium';
import pointImage from '@/assets/images/point.png';
import drone from '@/assets/images/drone.png';
import CesiumDrone from '@/assets/models/CesiumDrone.glb';
import DroneStaion from '@/assets/models/base_basic_pbr.glb';
import * as Cesium from "cesium";

class CesiumDrawTool {
    constructor(viewer, emit) {
        this.viewer = viewer;
        this.emit = emit;
        this.activeHandlers = [];
        this.activeColor = Color.RED; // 默认颜色
        this.currentDrawMode = null;

        // 存储手动绘制的实体
        this.manualDrawings = {
            points: [],    // 点 [{entity}]
            lines: [],     // 线 [{lineEntity, labelEntity}]
            surfaces: [],  // 面 [{polygonEntity, labelEntity}]
            tempPoints: [] // 临时点坐标（用于线和面的绘制过程）
        };

        // 存储数据加载的实体
        this.dataEntities = {
            points: [],
            lines: [],
            surfaces: []
        };

        this.trajectoryPointCount = 0;  // 轨迹点计数器
        this.trajectoryPoints = [];     // 存储轨迹点

        // 事件监听器
        this._eventListeners = {
            'draw-point': [],
            'draw-line': [],
            'draw-surface': [],
            'circle-update': [],
            'polygon-update': [],
            'entity-delete': [],
            'entity-hover': [],
            'data-point-click': [],
            'data-line-click': [],
            'data-surface-click': []
        };

        // 交互状态
        this.hoverLabel = null;
        this.deleteButton = null;
        this.selectedEntity = null;
        this.deleteClickHandler = null;
        // 初始化事件监听
        this.initEventListeners();
        this.setupClickEvents(); // 点线面左键点击事件监听
    }

    /** ========== 事件系统 ========== */
    //初始化事件监听
    initEventListeners() {
        this.setupHoverEvents();
        this.setupContextMenu();
    }

    // 添加事件监听
    on(eventName, callback) {
        if (this._eventListeners[eventName]) {
            this._eventListeners[eventName].push(callback);
        }
    }

    // 触发事件
    _emit(eventName, data) {
        if (this._eventListeners[eventName]) {
            this._eventListeners[eventName].forEach(cb => cb(data));
        }
        if (this.emit) {
            this.emit(eventName, data);
        }
    }

    // 设置当前颜色
    setActiveColor(hexColor) {
        this.activeColor = Color.fromCssColorString(hexColor);
    }

    // 完全重置
    resetAll() {
        this.cleanupHandlers();
        this.clearManualDrawings();
        this.clearDataEntities();
        this.currentDrawMode = null;
    }

    // 更新手动绘制点的颜色
    updateManualPointColor(color) {
        this.manualDrawings.points.forEach(point => {
            point.point.color = Color.fromCssColorString(color);
        });
    }

// 更新手动绘制线的颜色
    updateManualLineColor(color) {
        this.manualDrawings.lines.forEach(line => {
            if (line.lineEntity) {
                line.lineEntity.polyline.material = Color.fromCssColorString(color);
            }
        });
    }

// 更新手动绘制面的颜色
    updateManualSurfaceColor(color) {
        this.manualDrawings.surfaces.forEach(surface => {
            if (surface.polygonEntity) {
                surface.polygonEntity.polygon.material = Color.fromCssColorString(color).withAlpha(0.3);
            }
            if (surface.lineEntity) {
                surface.lineEntity.polyline.material = Color.fromCssColorString(color);
            }
        });
    }

    // 清除手动绘制的内容
    clearManualDrawings() {
        // 清除点
        this.manualDrawings.points.forEach(e => this.viewer.entities.remove(e));
        this.manualDrawings.points = [];

        // 清除线
        this.manualDrawings.lines.forEach(e => {
            if (e.lineEntity) this.viewer.entities.remove(e.lineEntity);
            if (e.labelEntity) this.viewer.entities.remove(e.labelEntity);
        });
        this.manualDrawings.lines = [];

        // 清除面
        this.manualDrawings.surfaces.forEach(e => {
            if (e.polygonEntity) this.viewer.entities.remove(e.polygonEntity);
            if (e.labelEntity) this.viewer.entities.remove(e.labelEntity);
        });
        this.manualDrawings.surfaces = [];

        // 清除临时点
        this.manualDrawings.tempPoints = [];
    }

    // 清除数据实体
    clearDataEntities() {
        // 清除点
        this.dataEntities.points.forEach(e => this.viewer.entities.remove(e));
        this.dataEntities.points = [];

        // 清除线
        this.dataEntities.lines.forEach(e => {
            if (e.lineEntity) this.viewer.entities.remove(e.lineEntity);
            if (e.labelEntity) this.viewer.entities.remove(e.labelEntity);
        });
        this.dataEntities.lines = [];

        // 清除面
        this.dataEntities.surfaces.forEach(e => {
            if (e.polygonEntity) this.viewer.entities.remove(e.polygonEntity);
            if (e.labelEntity) this.viewer.entities.remove(e.labelEntity);
        });
        this.dataEntities.surfaces = [];
    }

    /** ========== 交互事件 ========== */
    setupHoverEvents() {
        const handler = new ScreenSpaceEventHandler(this.viewer.scene.canvas);
        this.activeHandlers.push(handler);

        handler.setInputAction(movement => {
            // 清除之前悬停效果
            if (this.hoverLabel) {
                const originalText = this.hoverLabel._originalText || this.hoverLabel.label.text.getValue();
                this.hoverLabel.label.text = originalText;
                this.hoverLabel.label.showBackground = false;
                this.hoverLabel = null;
                this._emit('entity-hover', { isHovering: false });
            }

            const pickedObject = this.viewer.scene.pick(movement.endPosition);

            // 跳过绘制过程中的顶点和测量工具的顶点
            if (pickedObject && pickedObject.id &&
                (pickedObject.id.isDrawingVertex || pickedObject.id.isMeasureVertex)) {
                return;
            }

            if (pickedObject && pickedObject.id && pickedObject.id.label && pickedObject.id !== this.deleteButton) {
                this.hoverLabel = pickedObject.id;
                // 保存原始文本
                if (!this.hoverLabel._originalText) {
                    this.hoverLabel._originalText = this.hoverLabel.label.text.getValue();
                }
                this.hoverLabel.label.showBackground = true;
                this.hoverLabel.label.backgroundColor = Color.LIGHTGRAY.withAlpha(0.7);
                this.hoverLabel.label.text = '右键可删除';
                this._emit('entity-hover', {
                    isHovering: true,
                    entity: pickedObject.id
                });
            }
        }, ScreenSpaceEventType.MOUSE_MOVE);
    }

    setupContextMenu() {
        const handler = new ScreenSpaceEventHandler(this.viewer.scene.canvas);
        this.activeHandlers.push(handler);

        handler.setInputAction(movement => {
            this.cleanupDeleteButton();

            const pickedObject = this.viewer.scene.pick(movement.position);
            // 新增判断：如果是测量工具的顶点，直接跳过
            if (pickedObject && pickedObject.id && pickedObject.id.isMeasureVertex) return;

            if (pickedObject && pickedObject.id && pickedObject.id.label) {
                this.selectedEntity = pickedObject.id;
                this.createDeleteButton();
            }
        }, ScreenSpaceEventType.RIGHT_CLICK);
    }

    cleanupDeleteButton() {
        if (this.deleteButton) {
            this.viewer.entities.remove(this.deleteButton);
            this.deleteButton = null;
        }
        if (this.deleteClickHandler) {
            this.deleteClickHandler.destroy();
            const index = this.activeHandlers.indexOf(this.deleteClickHandler);
            if (index !== -1) this.activeHandlers.splice(index, 1);
            this.deleteClickHandler = null;
        }
    }

    // 在createDeleteButton方法中创建删除按钮时添加disableDepthTestDistance
    createDeleteButton() {
        if (!this.selectedEntity) return;

        // 清理现有的删除按钮
        this.cleanupDeleteButton();

        // 创建新的删除按钮
        this.deleteButton = this.viewer.entities.add({
            position: this.selectedEntity.position,
            label: {
                text: '× 删除',
                font: '14px sans-serif',
                fillColor: Color.RED,
                backgroundColor: Color.WHITE.withAlpha(0.8),
                showBackground: true,
                verticalOrigin: VerticalOrigin.BOTTOM,
                pixelOffset: new Cartesian2(0, -30),
                style: LabelStyle.FILL_AND_OUTLINE,
                outlineWidth: 2,
                outlineColor: Color.BLACK,
                disableDepthTestDistance: Number.POSITIVE_INFINITY
            }
        });

        // 创建点击处理器
        this.deleteClickHandler = new ScreenSpaceEventHandler(this.viewer.scene.canvas);
        this.activeHandlers.push(this.deleteClickHandler);

        // 添加点击事件
        this.deleteClickHandler.setInputAction(click => {
            const picked = this.viewer.scene.pick(click.position);
            if (picked && picked.id === this.deleteButton) {
                this.handleEntityDelete();
            }
        }, ScreenSpaceEventType.LEFT_CLICK);
    }

    handleEntityDelete() {
        if (!this.selectedEntity) {
            console.warn('No selected entity');
            return;
        }

        // 1. 解析实体ID前缀
        const entityId = this.selectedEntity.id;
        let type, rawId;

        if (typeof entityId === 'string') {
            const prefixMap = {
                'point_': 'point',
                'line_': 'line',
                'surface_': 'surface'
            };

            for (const [prefix, entityType] of Object.entries(prefixMap)) {
                if (entityId.startsWith(prefix)) {
                    type = entityType;
                    rawId = entityId.slice(prefix.length);
                    break;
                }
            }
        }

        // 2. 触发删除事件（传递原始ID）
        if (type && rawId) {
            this._emit('entity-delete', { type, id: rawId });
        } else {
            console.warn('Could not determine entity type or ID');
        }

        // 3. 清理删除按钮
        this.cleanupDeleteButton();
    }

    // 新增点击事件监听方法
    setupClickEvents() {
        const clickHandler = new ScreenSpaceEventHandler(this.viewer.scene.canvas);
        this.activeHandlers.push(clickHandler);

        clickHandler.setInputAction(click => {
            const pickedObject = this.viewer.scene.pick(click.position);
            if (pickedObject && pickedObject.id) {
                const entityId = pickedObject.id.id;
                if (typeof entityId === 'string') {
                    if (entityId.startsWith('point_')) {
                        this._emit('data-point-click', {
                            type: 'point',
                            id: entityId.replace('point_', ''),
                            entity: pickedObject.id
                        });
                    } else if (entityId.startsWith('line_')) {
                        this._emit('data-line-click', {
                            type: 'line',
                            id: entityId.replace('line_', ''),
                            entity: pickedObject.id
                        });
                    } else if (entityId.startsWith('surface_')) {
                        this._emit('data-surface-click', {
                            type: 'surface',
                            id: entityId.replace('surface_', ''),
                            entity: pickedObject.id
                        });
                    }
                }
            }
        }, ScreenSpaceEventType.LEFT_CLICK);
    }

    /******************** 绘制方法 ********************/

    // 绘制点（单次点击，仅保留最后一个点）
    drawPoint() {
        this.cleanupHandlers();
        this.currentDrawMode = 'point';

        const handler = new ScreenSpaceEventHandler(this.viewer.scene.canvas);
        this.activeHandlers.push(handler);

        handler.setInputAction(movement => {
            const cartesian = this.viewer.camera.pickEllipsoid(movement.position, this.viewer.scene.globe.ellipsoid);
            if (!cartesian) return;

            // 清除之前的手动绘制点（保留其他类型绘制内容）
            this.manualDrawings.points.forEach(point => this.viewer.entities.remove(point));
            this.manualDrawings.points = []; // 清空数组

            // 创建新点实体
            const pointEntity = this.viewer.entities.add({
                position: cartesian,
                point: {
                    pixelSize: 10,
                    color: this.activeColor,
                    outlineColor: Color.WHITE,
                    outlineWidth: 2
                }
            });

            this.manualDrawings.points.push(pointEntity); // 仅保留当前点

            // 转换坐标并触发事件（仅传递当前点坐标）
            const cartographic = Cartographic.fromCartesian(cartesian);
            this._emit('draw-point', {
                longitude: CesiumMath.toDegrees(cartographic.longitude),
                latitude: CesiumMath.toDegrees(cartographic.latitude)
            });
        }, ScreenSpaceEventType.LEFT_CLICK);
    }

    // 绘制线
    drawLine() {
        this.cleanupHandlers();
        this.clearManualDrawings();
        this.currentDrawMode = 'line';

        const handler = new ScreenSpaceEventHandler(this.viewer.scene.canvas);
        this.activeHandlers.push(handler);

        handler.setInputAction(movement => {
            const cartesian = this.viewer.camera.pickEllipsoid(movement.position, this.viewer.scene.globe.ellipsoid);
            if (!cartesian) return;

            this.manualDrawings.tempPoints.push(cartesian);
            const pointIndex = this.manualDrawings.tempPoints.length;

            // 添加点标签
            const labelEntity = this.viewer.entities.add({
                position: cartesian,
                label: {
                    text: `${pointIndex}`,
                    font: '14px sans-serif',
                    fillColor: Color.WHITE,
                    verticalOrigin: VerticalOrigin.BOTTOM
                },
                // 添加标识，表明这是绘制过程中的顶点标签
                isDrawingVertex: true
            });

            // 当有至少两个点时绘制线段
            if (this.manualDrawings.tempPoints.length >= 2) {
                const lineEntity = this.viewer.entities.add({
                    polyline: {
                        positions: [
                            this.manualDrawings.tempPoints[this.manualDrawings.tempPoints.length - 2],
                            this.manualDrawings.tempPoints[this.manualDrawings.tempPoints.length - 1]
                        ],
                        width: 2,
                        material: this.activeColor
                    }
                });

                this.manualDrawings.lines.push({ lineEntity, labelEntity });

                // 计算总长度
                let total = 0;
                for (let i = 1; i < this.manualDrawings.tempPoints.length; i++) {
                    total += Cartesian3.distance(
                        this.manualDrawings.tempPoints[i - 1],
                        this.manualDrawings.tempPoints[i]
                    );
                }

                this._emit('draw-line', {
                    points: this.getCartographicCoordinates(this.manualDrawings.tempPoints),
                    totalLength: total / 1000 // 转为公里
                });
            } else {
                this.manualDrawings.lines.push({ labelEntity });
            }
        }, ScreenSpaceEventType.LEFT_CLICK);
    }

    // 绘制面
    drawSurface() {
        this.cleanupHandlers();
        this.clearManualDrawings();
        this.currentDrawMode = 'surface';

        const handler = new ScreenSpaceEventHandler(this.viewer.scene.canvas);
        this.activeHandlers.push(handler);

        // 点击添加点
        handler.setInputAction(movement => {
            const cartesian = this.viewer.camera.pickEllipsoid(movement.position, this.viewer.scene.globe.ellipsoid);
            if (!cartesian) return;

            this.manualDrawings.tempPoints.push(cartesian);
            const pointIndex = this.manualDrawings.tempPoints.length;

            // 添加点标签
            const labelEntity = this.viewer.entities.add({
                position: cartesian,
                label: {
                    text: `${pointIndex}`,
                    font: '14px sans-serif',
                    fillColor: Color.WHITE
                },
                // 添加标识，表明这是绘制过程中的顶点标签
                isDrawingVertex: true
            });

            this.manualDrawings.surfaces.push({ labelEntity });

            // 实时更新面（至少3个点时）
            if (this.manualDrawings.tempPoints.length >= 3) {
                this.updateSurfacePolygon();
            }
        }, ScreenSpaceEventType.LEFT_CLICK);

        // 右键完成绘制
        /*handler.setInputAction(() => {
            if (this.manualDrawings.tempPoints.length >= 3) {
                this.updateSurfacePolygon(true);
                this.cleanupHandlers();
            }
        }, ScreenSpaceEventType.RIGHT_CLICK);*/
    }

    // 更新面绘制
    updateSurfacePolygon(final = false) {
        // 移除旧面
        this.manualDrawings.surfaces
            .filter(e => e.polygonEntity)
            .forEach(e => this.viewer.entities.remove(e.polygonEntity));

        // 创建新面
        const polygonEntity = this.viewer.entities.add({
            polygon: {
                hierarchy: this.manualDrawings.tempPoints,
                material: this.activeColor.withAlpha(0.3)
            }
        });

        // 计算面积
        const areaM2 = this.calculatePolygonArea(this.manualDrawings.tempPoints);

        // 更新面实体引用
        this.manualDrawings.surfaces.push({ polygonEntity });

        // 触发事件
        this._emit('draw-surface', {
            points: this.getCartographicCoordinates(this.manualDrawings.tempPoints),
            area: areaM2 / 1e6 // 转为平方公里
        });

        // 最终绘制闭合线
        if (final && this.manualDrawings.tempPoints.length >= 3) {
            const closingLine = this.viewer.entities.add({
                polyline: {
                    positions: [
                        this.manualDrawings.tempPoints[this.manualDrawings.tempPoints.length - 1],
                        this.manualDrawings.tempPoints[0]
                    ],
                    width: 2,
                    material: this.activeColor
                }
            });
            this.manualDrawings.surfaces.push({ lineEntity: closingLine });
        }
    }

    /******************** 数据加载方法 ********************/

    // 加载点数据
    drawPointFromData(pointData) {
        if (!pointData?.rows?.length) return;

        pointData.rows.forEach(row => {
            const { id, dLongitude, dLatitude, pointColor, pointName } = row;
            if (isNaN(dLongitude) || isNaN(dLatitude)) return;

            const pointEntity = this.viewer.entities.add({
                id: `point_${id}`, // 添加前缀
                position: Cartesian3.fromDegrees(dLongitude, dLatitude),
                point: {
                    pixelSize: 10,
                    color: Color.fromCssColorString(pointColor || '#FF0000'),
                    outlineColor: Color.WHITE,
                    outlineWidth: 2
                },
                label: {
                    text: pointName || '点',
                    font: '12px sans-serif',
                    fillColor: Color.BLACK,
                    verticalOrigin: VerticalOrigin.BOTTOM,
                    pixelOffset: new Cartesian2(0, -10),
                    showBackground: false,
                    disableDepthTestDistance: Number.POSITIVE_INFINITY // 确保标签始终可见
                }
            });

            this.dataEntities.points.push(pointEntity);
        });
    }

    // 2D机场
    drawgPointImg(point) {
        try {
            let id = point.id ? point.id : Math.random();
            return this.viewer.entities.add({
                id: id,
                position: Cartesian3.fromDegrees(point.lng, point.lat, point.alt),
                billboard: {
                    id: id,
                    image: drone,
                    horizontalOrigin: HorizontalOrigin.CENTER,
                    verticalOrigin: VerticalOrigin.BOTTOM,
                    scale: 1,
                    zIndex: 1,
                }
            });
        } catch (error) {
            console.error(error);
        }
    }

    //3D机场
    drawgPointDroneStation(point) {
        try {
            let id = point.id ? point.id : Math.random();
            return this.viewer.entities.add({
                id: id,
                position: Cartesian3.fromDegrees(point.lng, point.lat, point.alt),
                model: {
                    uri: DroneStaion,
                    //   minimumPixelSize: 200,
                    // maximumScale: 3000,
                         minimumPixelSize: 200,
                    maximumScale:1000,
                     scale: 1.0,
                    heightReference: HeightReference.CLAMP_TO_GROUND,
                      distanceDisplayCondition: new Cesium.DistanceDisplayCondition(0, 500000) // 500m~500km可见
                }
            });
        } catch (error) {
            console.error(error);
            return null;
        }
    }
    // 动态调整参数函数
 updateModelParameters(entity) {
    //3d 状态下的机场图标根据缩放控制显示大小
  const cameraHeight = this.viewer.camera.positionCartographic.height; // 相机高度（米）
  const zoomLevel = Math.log2(cameraHeight / 100); // 自定义缩放等级（示例公式）

  // 根据缩放等级动态设置参数
  if (zoomLevel < 10) { // 远距离（低缩放）
    entity.model.minimumPixelSize = 150;  // 最小像素尺寸降低
    entity.model.maximumScale = 600;    // 最大缩放倍数降低
  } else if (zoomLevel < 15) { // 中距离
    entity.model.minimumPixelSize = 130;
    entity.model.maximumScale = 400;
  } else { // 近距离（高缩放）
    entity.model.minimumPixelSize =100;
    entity.model.maximumScale =300;
  }
}

    // 清除指定机场实体
    clearDroneStation(entityOrId) {
        try {
            if (!entityOrId) return;

            // 如果传入的是实体ID
            if (typeof entityOrId === 'string' || typeof entityOrId === 'number') {
                const entity = this.viewer.entities.getById(entityOrId);
                if (entity) {
                    this.viewer.entities.remove(entity);
                }
            }
            // 如果传入的是实体对象
            else {
                this.viewer.entities.remove(entityOrId);
            }
        } catch (error) {
            console.error('清除机场实体失败:', error);
        }
    }

    // 添加一个同步获取地形高度的方法
    getTerrainHeight(longitude, latitude) {
        const cartographic = Cartographic.fromDegrees(longitude, latitude);
        const height = this.viewer.scene.globe.getHeight(cartographic) || 0;
        return height;
    }

// 修改 drawgDroneModel 方法
    drawgDroneModel(point) {
        try {
            if (this.viewer.scene.mode !== SceneMode.SCENE3D) {
                this.viewer.scene.mode = SceneMode.SCENE3D;
            }

            let id = point.id ? point.id : Math.random();
            const terrainHeight = this.getTerrainHeight(point.lng, point.lat);
            const position = Cartesian3.fromDegrees(point.lng, point.lat, point.alt);
            const groundPosition = Cartesian3.fromDegrees(point.lng, point.lat, terrainHeight);

            const droneEntity = this.viewer.entities.add({
                id: `drone_${id}`,
                position: position,
                model: {
                    uri: CesiumDrone,
                    minimumPixelSize: 50,
                    scale: 1.0
                }
            });

            const lineEntity = this.viewer.entities.add({
                id: `drone_line_${id}`,
                polyline: {
                    positions: [groundPosition, position],
                    width: 2,
                    material: new PolylineDashMaterialProperty({
                        color: Color.YELLOW.withAlpha(0.8),
                        dashLength: 16.0
                    })
                }
            });

            this.dataEntities.points.push(droneEntity);
            this.dataEntities.lines.push({
                id: `drone_line_${id}`,
                lineEntity: lineEntity
            });

            return droneEntity;

        } catch (error) {
            console.error('加载无人机模型失败:', error);
            return null;
        }
    }

// 修改 updateDronePosition 方法
    updateDronePosition(droneEntity, point) {
        if (!droneEntity) return null;

        const terrainHeight = this.getTerrainHeight(point.lng, point.lat);
        const endPosition = Cartesian3.fromDegrees(point.lng, point.lat, point.alt);
        const groundPosition = Cartesian3.fromDegrees(point.lng, point.lat, terrainHeight);
        const lineEntity = this.viewer.entities.getById(`drone_line_${droneEntity.id.replace('drone_', '')}`);

        droneEntity.position = endPosition;

        if (lineEntity) {
            lineEntity.polyline.positions = [groundPosition, endPosition];
        }

        // 处理轨迹点
        this.trajectoryPointCount++;
        if (this.trajectoryPointCount % 1 === 0) {
            const pointEntity = this.viewer.entities.add({
                position: endPosition,
                point: {
                    pixelSize: 8,
                    color: Color.YELLOW,
                    outlineColor: Color.WHITE,
                    outlineWidth: 2
                }
            });

            const verticalLineEntity = this.viewer.entities.add({
                polyline: {
                    positions: [groundPosition, endPosition],
                    width: 2,
                    material: new PolylineDashMaterialProperty({
                        color: Color.YELLOW.withAlpha(0.8),
                        dashLength: 16.0
                    })
                }
            });

            if (this.trajectoryPoints.length > 0) {
                const prevPoint = this.trajectoryPoints[this.trajectoryPoints.length - 1];
                this.viewer.entities.add({
                    polyline: {
                        positions: [prevPoint.position, endPosition],
                        width: 2,
                        material: new PolylineDashMaterialProperty({
                            color: Color.YELLOW.withAlpha(0.8),
                            dashLength: 16.0
                        })
                    }
                });
            }

            this.trajectoryPoints.push({
                position: endPosition,
                pointEntity: pointEntity,
                verticalLineEntity: verticalLineEntity
            });
        }

        // 相机视角设置
        this.viewer.camera.flyTo({
            destination: Cartesian3.fromDegrees(
                point.lng + 0.001,
                point.lat - 0.004,
                point.alt + 150
            ),
            orientation: {
                heading: CesiumMath.toRadians(0),
                pitch: CesiumMath.toRadians(-20),
                roll: 0
            },
            duration: 0.5,
            complete: () => {
                this.viewer.scene.screenSpaceCameraController.enableRotate = true;
                this.viewer.scene.screenSpaceCameraController.enableTranslate = true;
                this.viewer.scene.screenSpaceCameraController.enableZoom = true;
                this.viewer.scene.screenSpaceCameraController.enableTilt = true;
            }
        });
    }



    // 加载线数据
    drawLineFromData(lineData) {
        if (!lineData?.rows?.length) return;

        lineData.rows.forEach(row => {
            const { id, lineColor, points, lineName } = row;
            if (!points || points.length < 2) return;

            const positions = points.map(p => {
                const lon = parseFloat(p.xLongitude);
                const lat = parseFloat(p.xLatitude);
                return !isNaN(lon) && !isNaN(lat) ? Cartesian3.fromDegrees(lon, lat) : null;
            }).filter(Boolean);

            if (positions.length < 2) return;

            const lineEntity = this.viewer.entities.add({
                id: `line_${id}`, // 添加前缀
                polyline: {
                    positions: positions,
                    width: 2,
                    material: Color.fromCssColorString(lineColor || '#00FF00'),
                    clampToGround: true
                }
            });

            const midIndex = Math.floor(positions.length / 2);
            const labelEntity = this.viewer.entities.add({
                id: `line_${id}_label`, // 添加前缀
                position: positions[midIndex],
                label: {
                    text: lineName || '线',
                    font: '12px sans-serif',
                    fillColor: Color.BLACK,
                    verticalOrigin: VerticalOrigin.BOTTOM,
                    pixelOffset: new Cartesian2(0, -10),
                    showBackground: false,
                    disableDepthTestDistance: Number.POSITIVE_INFINITY
                }
            });

            this.dataEntities.lines.push({
                id: `line_${id}`, // 统一使用带前缀的ID
                lineEntity,
                labelEntity
            });
        });
    }

    // 加载面数据
    drawSurfaceFromData(surfaceData) {
        if (!surfaceData?.rows?.length) return;

        surfaceData.rows.forEach(row => {
            const { id, surfaceColor, points, surfaceName } = row;
            if (!points || points.length < 3) return;

            const positions = points.map(p => {
                const lon = parseFloat(p.mLongitude);
                const lat = parseFloat(p.mLatitude);
                return !isNaN(lon) && !isNaN(lat) ? Cartesian3.fromDegrees(lon, lat) : null;
            }).filter(Boolean);

            if (positions.length < 3) return;

            const center = positions.reduce((sum, pos) => {
                return Cartesian3.add(sum, pos, new Cartesian3());
            }, new Cartesian3());
            Cartesian3.divideByScalar(center, positions.length, center);

            const polygonEntity = this.viewer.entities.add({
                id: `surface_${id}_polygon`, // 添加前缀
                polygon: {
                    hierarchy: positions,
                    material: Color.fromCssColorString(surfaceColor || '#0000FF').withAlpha(0.3),
                    outline: true,
                    outlineColor: Color.BLACK
                }
            });

            const labelEntity = this.viewer.entities.add({
                id: `surface_${id}_label`, // 添加前缀
                position: center,
                label: {
                    text: surfaceName || '面',
                    font: '12px sans-serif',
                    fillColor: Color.BLACK,
                    verticalOrigin: VerticalOrigin.CENTER,
                    showBackground: false,
                    disableDepthTestDistance: Number.POSITIVE_INFINITY
                }
            });

            this.dataEntities.surfaces.push({
                id: `surface_${id}`, // 统一使用带前缀的ID
                polygonEntity,
                labelEntity
            });
        });
    }

    /******************** 辅助方法 ********************/

    // 坐标转换
    getCartographicCoordinates(points) {
        return points.map(p => {
            const carto = Cartographic.fromCartesian(p);
            return {
                longitude: CesiumMath.toDegrees(carto.longitude),
                latitude: CesiumMath.toDegrees(carto.latitude)
            };
        });
    }

    // 计算多边形面积
    calculatePolygonArea(points) {
        if (points.length < 3) return 0;

        try {
            const ellipsoid = this.viewer.scene.globe.ellipsoid;
            let totalArea = 0;

            for (let i = 1; i < points.length - 1; i++) {
                const p0 = Cartographic.fromCartesian(points[0], ellipsoid);
                const p1 = Cartographic.fromCartesian(points[i], ellipsoid);
                const p2 = Cartographic.fromCartesian(points[i + 1], ellipsoid);

                const geo1 = new EllipsoidGeodesic(p0, p1, ellipsoid);
                const geo2 = new EllipsoidGeodesic(p1, p2, ellipsoid);
                const geo3 = new EllipsoidGeodesic(p2, p0, ellipsoid);

                const a = geo1.surfaceDistance;
                const b = geo2.surfaceDistance;
                const c = geo3.surfaceDistance;

                const s = (a + b + c) / 2;
                totalArea += Math.sqrt(s * (s - a) * (s - b) * (s - c));
            }

            return totalArea;
        } catch (e) {
            console.error('面积计算错误:', e);
            return 0;
        }
    }


    // 控制数据实体的标签显示与隐藏（只影响数据加载的图形）
    toggleLabelsVisibility(isVisible) {
        // 数据点的标签
        this.dataEntities.points.forEach(pointEntity => {
            if (pointEntity.label) {
                pointEntity.label.show = isVisible;
            }
        });

        // 数据线的标签
        this.dataEntities.lines.forEach(({ labelEntity }) => {
            if (labelEntity?.label) {
                labelEntity.label.show = isVisible;
            }
        });

        // 数据面的标签
        this.dataEntities.surfaces.forEach(({ labelEntity }) => {
            if (labelEntity?.label) {
                labelEntity.label.show = isVisible;
            }
        });
    }

// 控制所有数据实体（包括图形和标签）的显示与隐藏
    toggleAllVisibility(isVisible) {
        // 数据点（图形+标签）
        this.dataEntities.points.forEach(pointEntity => {
            pointEntity.show = isVisible;
            if (pointEntity.label) {
                pointEntity.label.show = isVisible;
            }
        });

        // 数据线（图形+标签）
        this.dataEntities.lines.forEach(({ lineEntity, labelEntity }) => {
            if (lineEntity) lineEntity.show = isVisible;
            if (labelEntity?.label) labelEntity.label.show = isVisible;
        });

        // 数据面（图形+标签）
        this.dataEntities.surfaces.forEach(({ polygonEntity, labelEntity }) => {
            if (polygonEntity) polygonEntity.show = isVisible;
            if (labelEntity?.label) labelEntity.label.show = isVisible;
        });
    }

    // 控制手动绘制内容的标签显示与隐藏
    toggleManualLabelsVisibility(isVisible) {
        // 手动线的标签
        this.manualDrawings.lines.forEach(({ labelEntity }) => {
            if (labelEntity?.label) labelEntity.label.show = isVisible;
        });

        // 手动面的标签
        this.manualDrawings.surfaces.forEach(({ labelEntity }) => {
            if (labelEntity?.label) labelEntity.label.show = isVisible;
        });
    }

// 控制所有手动绘制内容（包括图形和标签）
    toggleManualAllVisibility(isVisible) {
        // 手动点
        this.manualDrawings.points.forEach(e => e.show = isVisible);

        // 手动线（图形+标签）
        this.manualDrawings.lines.forEach(({ lineEntity, labelEntity }) => {
            if (lineEntity) lineEntity.show = isVisible;
            if (labelEntity?.label) labelEntity.label.show = isVisible;
        });

        // 手动面（图形+标签）
        this.manualDrawings.surfaces.forEach(({ polygonEntity, labelEntity, lineEntity }) => {
            if (polygonEntity) polygonEntity.show = isVisible;
            if (labelEntity?.label) labelEntity.label.show = isVisible;
            if (lineEntity) lineEntity.show = isVisible;
        });
    }

    // 新增绘制定位图标方法
    drawLocationMarker(longitude, latitude) {
        return this.viewer.entities.add({
            position: Cartesian3.fromDegrees(longitude, latitude),
            billboard: {
                image: pointImage,
                width: 24,
                height: 24,
                verticalOrigin: VerticalOrigin.BOTTOM
            }
        });
    }

    // 绘制多边形
    drawPolygon() {
        this.cleanupHandlers();
        this.clearPolygon();

        this.drawingPolygon = true;
        this.polygonPoints = [];
        this.polygonEntities = [];

        const drawHandler = new ScreenSpaceEventHandler(this.viewer.scene.canvas);
        this.activeHandlers.push(drawHandler);

        // 点击添加点
        drawHandler.setInputAction((movement) => {
            const cartesian = this.viewer.camera.pickEllipsoid(movement.position, this.viewer.scene.globe.ellipsoid);
            if (cartesian) {
                this.polygonPoints.push(cartesian);
                const pointIndex = this.polygonPoints.length;

                // 添加点标签
                const labelEntity = this.viewer.entities.add({
                    position: cartesian,
                    label: new LabelGraphics({
                        text: `${pointIndex}`,
                        font: '14px sans-serif',
                        fillColor: Color.WHITE,
                        backgroundColor: Color.BLACK,
                        showBackground: true,
                        verticalOrigin: VerticalOrigin.BOTTOM,
                        pixelOffset: new Cartesian2(0, -10)
                    }),
                     // 添加标识，表明这是绘制过程中的顶点标签
                     isDrawingVertex: true
                });
                this.polygonEntities.push(labelEntity);

                // 添加线段（如果有至少两个点）
                if (this.polygonPoints.length >= 2) {
                    const polylineEntity = this.viewer.entities.add({
                        polyline: {
                            positions: [this.polygonPoints[this.polygonPoints.length - 2], this.polygonPoints[this.polygonPoints.length - 1]],
                            width: 2,
                            material: Color.RED
                        }
                    });
                    this.polygonEntities.push(polylineEntity);
                }
            }
        }, ScreenSpaceEventType.LEFT_CLICK);

        // 右键完成绘制
        drawHandler.setInputAction(() => {
            if (this.drawingPolygon && this.polygonPoints.length >= 3) {
                this.drawingPolygon = false;

                // 闭合多边形
                const closingLineEntity = this.viewer.entities.add({
                    polyline: {
                        positions: [this.polygonPoints[this.polygonPoints.length - 1], this.polygonPoints[0]],
                        width: 2,
                        material: Color.RED
                    }
                });
                this.polygonEntities.push(closingLineEntity);

                // 添加多边形面
                const polygonEntity = this.viewer.entities.add({
                    polygon: {
                        hierarchy: this.polygonPoints,
                        material: Color.LIGHTBLUE.withAlpha(0.5),
                        depthFailMaterial: new ColorMaterialProperty({
                            color: Color.LIGHTBLUE.withAlpha(0.5)
                        })
                    }
                });
                this.polygonEntities.push(polygonEntity);

                // 计算中心点
                const center = this.calculatePolygonCenter(this.polygonPoints);
                this.polygonCenter = center;

                // 发射事件
                const polygonPointsCoords = this.polygonPoints.map(point => {
                    const cartographic = this.viewer.scene.globe.ellipsoid.cartesianToCartographic(point);
                    return {
                        longitude: CesiumMath.toDegrees(cartographic.longitude),
                        latitude: CesiumMath.toDegrees(cartographic.latitude)
                    };
                });

                this.emit('polygon-update', {
                    polygonPoints: polygonPointsCoords,
                    polygonCenter: {
                        longitude: CesiumMath.toDegrees(center.longitude),
                        latitude: CesiumMath.toDegrees(center.latitude)
                    }
                });

                // 清理绘制处理器（保留实体）
                this.cleanupHandlers();
            }
        }, ScreenSpaceEventType.RIGHT_CLICK);
    }

    // 辅助函数：计算多边形中心
    calculatePolygonCenter(points) {
        const cartographics = points.map(point =>
            this.viewer.scene.globe.ellipsoid.cartesianToCartographic(point)
        );

        let sumLon = 0, sumLat = 0;
        cartographics.forEach(cartographic => {
            sumLon += cartographic.longitude;
            sumLat += cartographic.latitude;
        });

        return {
            longitude: sumLon / cartographics.length,
            latitude: sumLat / cartographics.length
        };
    }

    // 清除多边形
    clearPolygon() {
        if (this.polygonEntities && this.polygonEntities.length > 0) {
            this.polygonEntities.forEach(entity => this.viewer.entities.remove(entity));
            this.polygonEntities = [];
            this.polygonPoints = [];
            this.polygonCenter = null;
        }
    }

    // 绘制环形
    drawCircle() {
        this.cleanupHandlers();
        this.clearCircle();

        const handler = new ScreenSpaceEventHandler(this.viewer.scene.canvas);
        this.activeHandlers.push(handler);

        let isFirstClick = true;

        // 处理左键点击（绘制圆心/半径点）
        handler.setInputAction((movement) => {
            const cartesian = this.viewer.camera.pickEllipsoid(movement.position, this.viewer.scene.globe.ellipsoid);
            if (!cartesian) return;

            if (isFirstClick) {
                // 第一次点击 - 确定圆心
                this.circleCenter = cartesian;
                this.centerPointEntity = this.viewer.entities.add({
                    position: this.circleCenter,
                    point: { pixelSize: 10, color: Color.RED },
                      // 添加标识，表明这是绘制过程中的顶点
                      isDrawingVertex: true
                });
                isFirstClick = false;
            } else {
                // 第二次点击 - 确定半径
                this.radiusPoint = cartesian;
                this.updateCircleProperties();
                this.updateEntities();
                this.addDragHandlers();
                handler.destroy(); // 完成绘制后销毁主处理器
            }
        }, ScreenSpaceEventType.LEFT_CLICK);

        // 处理右键点击（取消绘制）
        handler.setInputAction((movement) => {
            if (!isFirstClick) { // 已确定圆心但未确定半径
                this.viewer.entities.remove(this.centerPointEntity);
                this.circleCenter = null;
                isFirstClick = true;
                handler.destroy(); // 销毁当前处理器
                this.activeHandlers = this.activeHandlers.filter(h => h !== handler);
            }
        }, ScreenSpaceEventType.RIGHT_CLICK);
    }

    updateCircleProperties() {
        const cartographicCenter = this.viewer.scene.globe.ellipsoid.cartesianToCartographic(this.circleCenter);
        const cartographicRadius = this.viewer.scene.globe.ellipsoid.cartesianToCartographic(this.radiusPoint);

        if (!cartographicCenter || !cartographicRadius) {
            console.log('坐标转换失败');
            return;
        }

        const centerLon = CesiumMath.toDegrees(cartographicCenter.longitude);
        const centerLat = CesiumMath.toDegrees(cartographicCenter.latitude);
        const radiusLon = CesiumMath.toDegrees(cartographicRadius.longitude);
        const radiusLat = CesiumMath.toDegrees(cartographicRadius.latitude);

        if (isNaN(centerLon) || isNaN(centerLat) || isNaN(radiusLon) || isNaN(radiusLat)) {
            console.log('经纬度计算结果包含无效值');
            return;
        }

        const R = 6371000; // 地球半径，单位：米
        const dLat = (radiusLat - centerLat) * (Math.PI / 180);
        const dLon = (radiusLon - centerLon) * (Math.PI / 180);
        const a =
            Math.sin(dLat / 2) * Math.sin(dLat / 2) +
            Math.cos(centerLat * (Math.PI / 180)) * Math.cos(radiusLat * (Math.PI / 180)) *
            Math.sin(dLon / 2) * Math.sin(dLon / 2);
        const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
        this.circleRadius = R * c;
        // 触发事件
        const cartographic = Cartographic.fromCartesian(this.circleCenter);
        this.emit('circle-update', {
            longitude: CesiumMath.toDegrees(cartographic.longitude),
            latitude: CesiumMath.toDegrees(cartographic.latitude),
            radius: this.circleRadius
        });
    }

    updateEntities() {
        this.removeExistingEntities();

        this.circleEntity = this.viewer.entities.add({
            position: this.circleCenter,
            ellipse: {
                semiMinorAxis: this.circleRadius,
                semiMajorAxis: this.circleRadius,
                material: Color.BLUE.withAlpha(0.5),
                outline: true,
                outlineColor: Color.BLACK,
                outlineWidth: 2,
                heightReference: HeightReference.CLAMP_TO_GROUND
            }
        });

        this.radiusPointEntity = this.viewer.entities.add({
            position: this.radiusPoint,
            point: {
                pixelSize: 10,
                color: Color.GREEN
            },
              // 添加标识，表明这是绘制过程中的顶点
              isDrawingVertex: true
        });

        this.radiusLineEntity = this.viewer.entities.add({
            polyline: {
                positions: [this.circleCenter, this.radiusPoint],
                width: 2,
                material: Color.YELLOW
            }
        });

        const midPoint = Cartesian3.midpoint(this.circleCenter, this.radiusPoint, new Cartesian3());
        this.radiusLabelEntity = this.viewer.entities.add({
            position: midPoint,
            label: {
                text: `半径：${this.circleRadius.toFixed(2)} 米`,
                font: '14px sans-serif',
                fillColor: Color.YELLOW,
                backgroundColor: Color.BLACK,
                showBackground: true,
                verticalOrigin: VerticalOrigin.BOTTOM,
                pixelOffset: new Cartesian2(0, -10)
            },
              // 添加标识，表明这是绘制过程中的顶点
              isDrawingVertex: true
        });
    }

    removeExistingEntities() {
        if (this.circleEntity) this.viewer.entities.remove(this.circleEntity);
        if (this.radiusPointEntity) this.viewer.entities.remove(this.radiusPointEntity);
        if (this.radiusLineEntity) this.viewer.entities.remove(this.radiusLineEntity);
        if (this.radiusLabelEntity) this.viewer.entities.remove(this.radiusLabelEntity);
    }

    addDragHandlers() {
        const dragHandler = new ScreenSpaceEventHandler(this.viewer.scene.canvas);
        let isDragging = false;
        let draggedEntity = null;

        dragHandler.setInputAction((movement) => {
            const pickedObject = this.viewer.scene.pick(movement.position);
            if (pickedObject && (pickedObject.id === this.centerPointEntity || pickedObject.id === this.radiusPointEntity)) {
                isDragging = true;
                draggedEntity = pickedObject.id;
                this.disableCameraControls();
            }
        }, ScreenSpaceEventType.LEFT_DOWN);

        dragHandler.setInputAction((movement) => {
            if (isDragging) {
                const newCartesian = this.viewer.camera.pickEllipsoid(movement.endPosition, this.viewer.scene.globe.ellipsoid);
                if (!newCartesian) {
                    console.log('拖拽时未能成功拾取到有效坐标');
                    return;
                }

                if (draggedEntity === this.centerPointEntity) {
                    this.moveCenter(newCartesian);
                } else if (draggedEntity === this.radiusPointEntity) {
                    this.moveRadiusPoint(newCartesian);
                }
            }
        }, ScreenSpaceEventType.MOUSE_MOVE);

        dragHandler.setInputAction(() => {
            if (isDragging) {
                isDragging = false;
                draggedEntity = null;
                this.enableCameraControls();
                this.logLatestCircleInfo();
            }
        }, ScreenSpaceEventType.LEFT_UP);
    }

    disableCameraControls() {
        this.viewer.scene.screenSpaceCameraController.enableRotate = false;
        this.viewer.scene.screenSpaceCameraController.enableTranslate = false;
        this.viewer.scene.screenSpaceCameraController.enableZoom = false;
        this.viewer.scene.screenSpaceCameraController.enableTilt = false;
        this.viewer.scene.screenSpaceCameraController.enableLook = false;
    }

    enableCameraControls() {
        this.viewer.scene.screenSpaceCameraController.enableRotate = true;
        this.viewer.scene.screenSpaceCameraController.enableTranslate = true;
        this.viewer.scene.screenSpaceCameraController.enableZoom = true;
        this.viewer.scene.screenSpaceCameraController.enableTilt = true;
        this.viewer.scene.screenSpaceCameraController.enableLook = true;
    }

    moveCenter(newCartesian) {
        const delta = Cartesian3.subtract(newCartesian, this.circleCenter, new Cartesian3());
        this.circleCenter = newCartesian;
        this.centerPointEntity.position = newCartesian;
        this.radiusPoint = Cartesian3.add(this.radiusPoint, delta, new Cartesian3());
        this.radiusPointEntity.position = newCartesian;
        this.circleEntity.position = newCartesian;
        this.radiusLineEntity.polyline.positions = [this.circleCenter, this.radiusPoint];
        this.updateMidpointAndLabel();
    }

    moveRadiusPoint(newCartesian) {
        this.radiusPoint = newCartesian;
        this.radiusPointEntity.position = newCartesian;
        this.updateCircleProperties();
        this.circleEntity.ellipse.semiMinorAxis = this.circleRadius;
        this.circleEntity.ellipse.semiMajorAxis = this.circleRadius;
        this.radiusLineEntity.polyline.positions = [this.circleCenter, this.radiusPoint];
        this.updateMidpointAndLabel();
    }

    updateMidpointAndLabel() {
        const midPoint = Cartesian3.midpoint(this.circleCenter, this.radiusPoint, new Cartesian3());
        this.radiusLabelEntity.position = midPoint;
        this.radiusLabelEntity.label.text = `半径：${this.circleRadius.toFixed(2)} 米`;

        // 触发事件（添加在函数末尾）
        const cartographic = Cartographic.fromCartesian(this.circleCenter);
        this.emit('circle-update', {
            longitude: CesiumMath.toDegrees(cartographic.longitude),
            latitude: CesiumMath.toDegrees(cartographic.latitude),
            radius: this.circleRadius
        });
    }

    logLatestCircleInfo() {
        console.log('最新圆心位置:', {
            longitude: CesiumMath.toDegrees(Cartographic.fromCartesian(this.circleCenter).longitude),
            latitude: CesiumMath.toDegrees(Cartographic.fromCartesian(this.circleCenter).latitude)
        });
        console.log('最新圆的半径:', this.circleRadius);
    }

    // 清除环形
    clearCircle() {
        if (this.circleEntity) this.viewer.entities.remove(this.circleEntity);
        if (this.centerPointEntity) this.viewer.entities.remove(this.centerPointEntity);
        if (this.radiusPointEntity) this.viewer.entities.remove(this.radiusPointEntity);
        if (this.radiusLineEntity) this.viewer.entities.remove(this.radiusLineEntity);
        if (this.radiusLabelEntity) this.viewer.entities.remove(this.radiusLabelEntity);

        // 重置所有环形相关变量
        this.circleEntity = null;
        this.centerPointEntity = null;
        this.radiusPointEntity = null;
        this.radiusLineEntity = null;
        this.radiusLabelEntity = null;
        this.circleCenter = null;
        this.radiusPoint = null;
        this.circleRadius = 0;
    }

    // 清理处理器的方法
    cleanupHandlers() {
        this.activeHandlers.forEach(handler => {
            try {
                handler.destroy();
            } catch (e) {
                console.warn("Error destroying handler:", e);
            }
        });
        this.activeHandlers = [];
        this.viewer.scene.screenSpaceCameraController.enableInputs = true; // 确保相机控制恢复
        // 重新初始化事件监听
        this.initEventListeners();
        this.setupClickEvents(); // 点线面左键点击事件监听
    }

    // 清除绘制状态监视器的方法
    resetDrawingState() {
        this.cleanupHandlers();
        // 重置多边形绘制状态
        this.drawingPolygon = false;
        this.polygonPoints = [];
        if (this.polygonEntities) {
            this.polygonEntities.forEach(entity => this.viewer.entities.remove(entity));
        }
        this.polygonEntities = [];
        this.polygonCenter = null;

        // 重置圆形绘制状态
        this.clearCircle();
    }

    // 根据经纬度画多边形
    drawExistingPolygon(points) {
        const entities = [];

        // 转换坐标点
        const cartesianPoints = points.map(p =>
            Cartesian3.fromDegrees(p[0], p[1])
        );

        // 创建多边形面
        const polygonEntity = this.viewer.entities.add({
            id: createGuid(), // 生成唯一的 ID
            polygon: {
                hierarchy: cartesianPoints,
                material: Color.RED.withAlpha(0.3),
                heightReference: HeightReference.CLAMP_TO_GROUND,
                outline: false,
            },
            allowPicking: false
        });
        entities.push(polygonEntity);

        return entities;
    }

    // 根据经纬度和半径画圆(用于2D机场)
    drawExistingCircle(longitude, latitude, radius) {
        const entities = [];
        const center = Cartesian3.fromDegrees(longitude, latitude);

        // 创建圆形
        return this.viewer.entities.add({
            id: createGuid(), // 生成唯一的 ID
            position: center,
            ellipse: {
                semiMinorAxis: radius,
                semiMajorAxis: radius,
                material: Color.BLUE.withAlpha(0.3),
                outline: false,
                heightReference: HeightReference.CLAMP_TO_GROUND
            },
            allowPicking: false
        });

    }

    // 根据经纬度和半径画圆(用于环形禁飞区)
    drawExistingCircleJFQ(longitude, latitude, radius) {
        const entities = [];
        const center = Cartesian3.fromDegrees(longitude, latitude);

        // 创建圆形
        const ellipseEntity = this.viewer.entities.add({
            id: createGuid(), // 生成唯一的 ID
            position: center,
            ellipse: {
                semiMinorAxis: radius,
                semiMajorAxis: radius,
                material: Color.BLUE.withAlpha(0.3),
                outline: false,
                heightReference: HeightReference.CLAMP_TO_GROUND
            },
            allowPicking: false
        });
        entities.push(ellipseEntity);

        return entities;
    }


    // 适用于2D模式的视角跳转方法（基础方法）
    flyToCenter(center, range) {
        const [lon, lat] = center;

        const rectangle = Rectangle.fromDegrees(
            lon - range,      // 左
            lat - range * 0.5, // 下（保持宽高比例）
            lon + range,      // 右
            lat + range * 0.5  // 上
        );

        this.viewer.camera.flyTo({
            destination: rectangle,
            duration: 1,
            easingFunction: EasingFunction.LINEAR
        });
    }

    // 针对环形区域的跳转
    flyToCircle(center, radius) {
        // 将半径转换为范围（单位：度）
        // 1000米 ≈ 0.009度（赤道附近）
        const rangeInDegrees = radius / 1000 * 0.009;
        // 保证最小范围0.3度，最大范围2度
        const range = Math.min(2, Math.max(0.05, rangeInDegrees * 3));
        this.flyToCenter(center, range);
    }

    // 针对多边形区域的跳转
    flyToPolygon(center) {
        // 固定范围为0.05度
        this.flyToCenter(center, 0.05);
    }

    getViewer() {
        return this.viewer;
    }

    // 加载默认禁飞区（标记为默认分组）
    loadDefaultNoFlyZones(data) {
        const defaultEntities = [];
        const GROUP_ID = "default_no_fly_zone"; // 分组标识

        data.features.forEach(feature => {
            const coordinates = feature.geometry.coordinates[0];
            const points = coordinates.map(coord => [coord[0], coord[1]]);
            const entities = this.drawExistingPolygon(points);

            // 标记为默认禁飞区（不依赖修改 id）
            entities.forEach(entity => {
                entity.customData = {
                    isDefaultNoFlyZone: true, // 自定义分组标识
                    groupId: GROUP_ID       // 可选：更精细的分组控制
                };
            });

            defaultEntities.push(...entities);
        });
        return defaultEntities;
    }

    // 清除默认禁飞区（高性能完整删除版）
    clearDefaultNoFlyZones() {
        const GROUP_ID = "default_no_fly_zone";

        // 1. 收集所有要删除的实体ID（比直接操作实体更快）
        const idsToRemove = [];
        this.viewer.entities.values.forEach(entity => {
            if (entity.customData?.isDefaultNoFlyZone) {
                idsToRemove.push(entity.id);
            }
        });

        // 2. 批量删除（分块处理避免UI冻结）
        const CHUNK_SIZE = 50; // 每批删除50个
        this.viewer.entities.suspendEvents();

        for (let i = 0; i < idsToRemove.length; i += CHUNK_SIZE) {
            const chunk = idsToRemove.slice(i, i + CHUNK_SIZE);
            chunk.forEach(id => {
                this.viewer.entities.removeById(id);
            });

            // 3. 强制场景立即更新
            this.viewer.scene.requestRender();
        }

        this.viewer.entities.resumeEvents();
    }

    // 添加水波纹扩散效果
    addCircleWaveEffect(longitude, latitude, options = {}) {
        // 定义水波纹材质
        const CircleWaveMaterialProperty = this.getCircleWaveMaterialProperty();

        // 创建水波纹实体
        return this.viewer.entities.add({
            position: Cartesian3.fromDegrees(longitude, latitude, options.height || 100),
            ellipse: {
                semiMinorAxis: options.radius || 1000,
                semiMajorAxis: options.radius || 1000,
                height: options.height || 10,
                material: new CircleWaveMaterialProperty({
                    color:  '#337aff',
                    duration: options.duration || 3000,
                    gradient: options.gradient || 0,
                    count: options.count || 4,
                }),
            },
        });
    }


    // 获取水波纹材质属性定义
    getCircleWaveMaterialProperty() {
        // 如果材质已经定义，直接返回
        if (this._circleWaveMaterialProperty) {
            return this._circleWaveMaterialProperty;
        }

        // 定义材质属性
        const CircleWaveMaterialProperty = function(options) {
            this._definitionChanged = new Cesium.Event();
            this.color = options.color && new Color.fromCssColorString(options.color) || Color.RED;
            this.duration = Cesium.defaultValue(options.duration, 1000);
            this.count = Math.max(1, Cesium.defaultValue(options.count, 2));
            this.gradient = Math.min(1, Cesium.defaultValue(options.gradient, 0.1));
            this.time = new Date().getTime();
        };

        Object.defineProperties(CircleWaveMaterialProperty.prototype, {
            isConstant: {
                get: function () {
                    return false;
                },
            },
            definitionChanged: {
                get: function () {
                    return this._definitionChanged;
                },
            },
            color: Cesium.createPropertyDescriptor('color'),
            gradient: Cesium.createPropertyDescriptor('gradient'),
            duration: Cesium.createPropertyDescriptor('duration'),
            count: Cesium.createPropertyDescriptor('count'),
        });

        CircleWaveMaterialProperty.prototype.getType = function () {
            return 'CircleWaveMaterial';
        };

        CircleWaveMaterialProperty.prototype.getValue = function (time, result) {
            if (!Cesium.defined(result)) {
                result = {};
            }
            result.color = Cesium.Property.getValueOrClonedDefault(this.color, time, Color.WHITE, result.color);
            result.time = ((new Date().getTime() - this.time) % this.duration) / this.duration;
            result.count = this.count;
            result.gradient = 1 + 10 * (1 - this.gradient);
            return result;
        };

        CircleWaveMaterialProperty.prototype.equals = function (other) {
            return this === other ||
                (other instanceof CircleWaveMaterialProperty &&
                    Cesium.Property.equals(this.color, other.color) &&
                    Cesium.Property.equals(this.duration, other.duration) &&
                    Cesium.Property.equals(this.count, other.count) &&
                    Cesium.Property.equals(this.gradient, other.gradient));
        };

        // 定义材质
        Cesium.Material._materialCache.addMaterial('CircleWaveMaterial', {
            fabric: {
                type: 'CircleWaveMaterial',
                uniforms: {
                    color: new Color(1.0, 1.0, 1.0, 1.0),
                    time: 1,
                    count: 1,
                    gradient: 0.1,
                },
                source: `
                    czm_material czm_getMaterial(czm_materialInput materialInput) {
                        czm_material material = czm_getDefaultMaterial(materialInput);
                        material.diffuse = 1.5 * color.rgb;
                        vec2 st = materialInput.st;
                        vec3 str = materialInput.str;
                        float dis = distance(st, vec2(0.5, 0.5));
                        float per = fract(time);
                        if (abs(str.z) > 0.001) {
                            discard;
                        }
                        if (dis > 0.5) {
                            discard;
                        } else {
                            float perDis = 0.5 / count;
                            float disNum;
                            float bl = .0;
                            for (int i = 0; i <= 9; i++) {
                                if (float(i) <= count) {
                                    disNum = perDis *float(i) - dis + per / count;
                                    if (disNum > 0.0) {
                                        if (disNum < perDis) {
                                            bl = 1.0 - disNum / perDis;
                                        } else if(disNum - perDis < perDis) {
                                            bl = 1.0 - abs(1.0 - disNum / perDis);
                                        }
                                        material.alpha = pow(bl, gradient);
                                    }
                                }
                            }
                        }
                        return material;
                    }
                `
            },
            translucent: function () {
                return true;
            },
        });

        // 缓存材质属性定义
        this._circleWaveMaterialProperty = CircleWaveMaterialProperty;
        return CircleWaveMaterialProperty;
    }

    // 删除所有水波纹效果
    removeAllCircleWaveEffects() {
        const entitiesToRemove = this.viewer.entities.values.filter(entity =>
            entity.ellipse &&
            entity.ellipse.material &&
            entity.ellipse.material.getType &&
            entity.ellipse.material.getType() === 'CircleWaveMaterial'
        );

        entitiesToRemove.forEach(entity => {
            this.viewer.entities.remove(entity);
        });

        return entitiesToRemove.length;
    }


}

export default CesiumDrawTool;
